﻿using DocumentFormat.OpenXml.Office2010.ExcelAc;
using ERP.Common.DTO;
using ERP.ERPSystem.ProductionSystem.MaterialTypes;
using ERP.Team.ProductionSystem;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using ERP.ERPSystem.ProductionSystem.Dto;
using System.Threading.Tasks;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 物料产品分类控制器
    /// </summary>
    [Route("[controller]/[action]")]
    public class MaterialTypeController : Controller
    {
        /// <summary>
        /// 物料产品分类服务接口
        /// </summary>
        private readonly IMaterialTypeService _typeService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="typeService">物料产品分类服务接口</param>
        public MaterialTypeController(IMaterialTypeService typeService)
        {
            this._typeService = typeService;
        }

        /// <summary>
        /// 物料产品分类视图
        /// </summary>
        /// <returns>视图</returns>
        [HttpGet]
        public IActionResult MaterialTypeIndex()
        {
            return View();
        }

        /// <summary>
        /// 获取分类树形结构（递归构建）
        /// </summary>
        /// <returns>分类树形列表，包含父子层级关系</returns>
        [Route("GetTreeAsync")]
        [HttpGet]
        public async Task<List<MaterialTypeDTO>> GetTreeAsync()
        {
            return await _typeService.GetTreeAsync();
        }

        /// <summary>
        /// 选择要添加的父级
        /// </summary>
        /// <returns>返回数据</returns>
        [Route("GetMaterialTypes")]
        [HttpGet]
        public async Task<List<MaterialType>> GetMaterialTypes()
        {
            return await _typeService.GetMaterialTypes();
        }

        /// <summary>
        /// 根据 ID 获取分类详情
        /// </summary>
        /// <param name="id">分类 ID</param>
        /// <returns>分类实体，若不存在则返回 null</returns>
        [Route("GetByIdAsync")]
        [HttpGet]
        public async Task<MaterialType> GetByIdAsync(int id)
        {
            return await _typeService.GetByIdAsync(id);
        }

        /// <summary>
        /// 新增或修改分类
        /// </summary>
        /// <param name="entity">分类实体（新增时 ID=0，修改时需携带已有 ID）</param>
        /// <returns>操作是否成功（默认返回 true，实际可根据仓储返回值调整）</returns>
        [Route("SaveAsync")]
        [HttpPost]
        public async Task<bool> SaveAsync([FromBody] MaterialTypeAddDTO entity)
        {
            return await _typeService.SaveAsync(entity);
        }

        /// <summary>
        /// 删除分类（递归删除所有子分类）
        /// </summary>
        /// <param name="id">待删除的分类 ID</param>
        /// <returns>操作是否成功（默认返回 true，实际可根据仓储返回值调整）</returns>
        [Route("DeleteAsync")]
        [HttpPost]
        public async Task<bool> DeleteAsync(int id)
        {
            return await _typeService.DeleteAsync(id);
        }

        /// <summary>
        /// 分页查询分类列表（支持搜索和状态筛选）
        /// </summary>
        /// <param name="keyword">分类名称关键词（模糊匹配）</param>
        /// <param name="isEnabled">是否启用（true=启用，false=禁用，null=不筛选）</param>
        /// <returns>分页结果（包含总数和当前页数据）</returns>
        [Route("GetPagedListAsync")]
        [HttpGet]
        public async Task<List<MaterialType>> GetPagedListAsync(string keyword = null, bool? isEnabled = null)
        {
            return await _typeService.GetPagedListAsync(keyword, isEnabled);
        }


        private List<MaterialTypeTreeDto> ConvertToTreeDto(List<MaterialType> types)
        {
            if (types == null || !types.Any())
                return new List<MaterialTypeTreeDto>();

            return types.Select(t => new MaterialTypeTreeDto
            {
                Id = t.Id,
                Title = t.MaterialTypeName,
                ParentId = t.ParentId,
                Index = t.Index,
                Children = ConvertToTreeDto(t.Children?.ToList())
            }).OrderBy(t => t.Index).ToList();
        }


        /// <summary>
        /// 分页查询分类列表（支持搜索和状态筛选）
        /// </summary>
        /// <param name="keyword">分类名称关键词（模糊匹配）</param>
        /// <param name="isEnabled">是否启用（true=启用，false=禁用，null=不筛选）</param>
        /// <param name="page">页码（从 1 开始）</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>分页结果（包含总数和当前页数据）</returns>
        [Route("GetPagedMaterialTypesAsync")]
        [HttpGet]
        public async Task<IActionResult> GetPagedMaterialTypesAsync(string keyword = null, bool? isEnabled = null, int page = 1, int pageSize = 10)
        {
            var result = await _typeService.GetPagedMaterialTypesAsync(keyword, isEnabled, page, pageSize);
            return Ok(result);
        }

        ///// <summary>
        ///// 获取某节点的所有子节点（递归）
        ///// </summary>
        //[Route("/MaterialType/GetAllChildrenAsync")]
        //[HttpGet]
        //public async Task<IActionResult> GetAllChildrenAsync(int id)
        //{
        //    var all = await _typeService.GetTreeAsync();
        //    var node = FindNode(all, id);
        //    if (node == null) return NotFound();
        //    // 递归获取所有子节点
        //    var children = GetAllChildren(node);
        //    return Ok(children);
        //}

        ///// <summary>
        ///// 获取某节点到根节点的路径
        ///// </summary>
        //[Route("/MaterialType/GetPathAsync")]
        //[HttpGet]
        //public async Task<IActionResult> GetPathAsync(int id)
        //{
        //    var all = await _typeService.GetTreeAsync();
        //    var flatList = Flatten(all);
        //    var node = flatList.FirstOrDefault(x => x.Id == id);
        //    if (node == null) return NotFound();
        //    var path = GetPath(node, flatList);
        //    return Ok(path);
        //}

        // 辅助方法：递归查找节点
        private MaterialType FindNode(IEnumerable<MaterialType> nodes, int id)
        {
            foreach (var node in nodes)
            {
                if (node.Id == id) return node;
                var found = FindNode(node.Children, id);
                if (found != null) return found;
            }
            return null;
        }

        // 辅助方法：递归获取所有子节点
        private List<MaterialType> GetAllChildren(MaterialType node)
        {
            var result = new List<MaterialType>();
            foreach (var child in node.Children)
            {
                result.Add(child);
                result.AddRange(GetAllChildren(child));
            }
            return result;
        }

        // 辅助方法：将树形结构拍平成列表
        private List<MaterialType> Flatten(IEnumerable<MaterialType> nodes)
        {
            var list = new List<MaterialType>();
            foreach (var node in nodes)
            {
                list.Add(node);
                list.AddRange(Flatten(node.Children));
            }
            return list;
        }

        // 辅助方法：获取路径
        private List<MaterialType> GetPath(MaterialType node, List<MaterialType> all)
        {
            var path = new List<MaterialType> { node };
            var current = node;
            while (current.ParentId != null)
            {
                var parent = all.FirstOrDefault(m => m.Id == current.ParentId);
                if (parent == null) break;
                path.Insert(0, parent);
                current = parent;
            }
            return path;
        }


        /// <summary>
        /// 分页查询分类列表（支持搜索和状态筛选）
        /// </summary>
        /// <param name="keyword">分类名称关键词（模糊匹配）</param>
        /// <param name="isEnabled">是否启用（true=启用，false=禁用，null=不筛选）</param>
        /// <returns>分页结果（包含总数和当前页数据）</returns>
        //[Route("GetPagedListAsync")]
        //[HttpGet]
        //public async Task<List<MaterialType>> GetPagedListAsync(string keyword = null, bool? isEnabled = null)
        //{
        //    return await _typeService.GetPagedListAsync(keyword, isEnabled);
        //}



        //---------------------------------------------------------------------------

        /// <summary>
        /// 物料产品分类视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult MaterialTypeIndexgrx()
        {
            return View();
        }

        /// <summary>
        /// 获取分类树形结构
        /// </summary>
        /// <returns>分类树形列表</returns>
        [Route("/MaterialType/GetTreeAsyncgrx")]
        [HttpGet]
        public async Task<JsonResult> GetTreeAsyncgrx()
        {
            var types = await _typeService.GetTreeAsyncgrx();
            var treeData = ConvertToTreeDtogrx(types);
            return Json(treeData);
        }

        private List<MaterialTypeTreeDto> ConvertToTreeDtogrx(List<MaterialType> types)
        {
            if (types == null || !types.Any())
                return new List<MaterialTypeTreeDto>();

            return types.Select(t => new MaterialTypeTreeDto
            {
                Id = t.Id,
                Title = t.MaterialTypeName,
                ParentId = t.ParentId,
                Index = t.Index,
                Children = ConvertToTreeDtogrx(t.Children?.ToList())
            }).OrderBy(t => t.Index).ToList();
        }

        /// <summary>
        /// 根据 ID 获取分类详情
        /// </summary>
        /// <param name="id">分类 ID</param>
        /// <returns>分类实体，若不存在则返回 null</returns>
        [Route("/MaterialType/GetByIdAsyncgrx")]
        [HttpGet]
        public async Task<MaterialType> GetByIdAsyncgrx(int id)
        {
            return await _typeService.GetByIdAsyncgrx(id);
        }

        /// <summary>
        /// 新增或修改分类
        /// </summary>
        /// <param name="entity">分类实体（新增时 ID=0，修改时需携带已有 ID）</param>
        /// <returns>操作是否成功（默认返回 true，实际可根据仓储返回值调整）</returns>
        [Route("/MaterialType/SaveAsyncgrx")]
        [HttpPost]
        public async Task<bool> SaveAsyncgrx([FromBody] MaterialTypeAddDTO entity)
        {
            return await _typeService.SaveAsyncgrx(entity);
        }

        /// <summary>
        /// 删除分类（递归删除所有子分类）
        /// </summary>
        /// <param name="id">待删除的分类 ID</param>
        /// <returns>操作是否成功（默认返回 true，实际可根据仓储返回值调整）</returns>
        [Route("/MaterialType/DeleteAsyncgrx")]
        [HttpPost]
        public async Task<bool> DeleteAsyncgrx(int id)
        {
            return await _typeService.DeleteAsyncgrx(id);
        }

        /// <summary>
        /// 分页查询分类列表（支持搜索和状态筛选）
        /// </summary>
        /// <param name="keyword">分类名称关键词（模糊匹配）</param>
        /// <param name="isEnabled">是否启用（true=启用，false=禁用，null=不筛选）</param>
        /// <param name="page">页码（从 1 开始）</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>分页结果（包含总数和当前页数据）</returns>
        [Route("/MaterialType/GetPagedListAsyncgrx")]
        [HttpGet]
        public async Task<IActionResult> GetPagedListAsyncgrx(string keyword = null, bool? isEnabled = null, int page = 1, int pageSize = 10)
        {
            var result = await _typeService.GetPagedListAsyncgrx(keyword, isEnabled, page, pageSize);
            return Ok(result);
        }

        /// <summary>
        /// 获取某节点的所有子节点（递归）
        /// </summary>
        [Route("/MaterialType/GetAllChildrenAsyncgrx")]
        [HttpGet]
        public async Task<IActionResult> GetAllChildrenAsyncgrx(int id)
        {
            var all = await _typeService.GetTreeAsyncgrx();
            var node = FindNodegrx(all, id);
            if (node == null) return NotFound();
            // 递归获取所有子节点
            var children = GetAllChildren(node);
            return Ok(children);
        }

        /// <summary>
        /// 获取某节点到根节点的路径
        /// </summary>
        [Route("/MaterialType/GetPathAsyncgrx")]
        [HttpGet]
        public async Task<IActionResult> GetPathAsyncgrx(int id)
        {
            var all = await _typeService.GetTreeAsyncgrx();
            var flatList = Flattengrx(all);
            var node = flatList.FirstOrDefault(x => x.Id == id);
            if (node == null) return NotFound();
            var path = GetPathgrx(node, flatList);
            return Ok(path);
        }

        // 辅助方法：递归查找节点
        private MaterialType FindNodegrx(IEnumerable<MaterialType> nodes, int id)
        {
            foreach (var node in nodes)
            {
                if (node.Id == id) return node;
                var found = FindNodegrx(node.Children, id);
                if (found != null) return found;
            }
            return null;
        }

        // 辅助方法：递归获取所有子节点
        private List<MaterialType> GetAllChildrengrx(MaterialType node)
        {
            var result = new List<MaterialType>();
            foreach (var child in node.Children)
            {
                result.Add(child);
                result.AddRange(GetAllChildrengrx(child));
            }
            return result;
        }

        // 辅助方法：将树形结构拍平成列表
        private List<MaterialType> Flattengrx(IEnumerable<MaterialType> nodes)
        {
            var list = new List<MaterialType>();
            foreach (var node in nodes)
            {
                list.Add(node);
                list.AddRange(Flattengrx(node.Children));
            }
            return list;
        }

        // 辅助方法：获取路径
        private List<MaterialType> GetPathgrx(MaterialType node, List<MaterialType> all)
        {
            var path = new List<MaterialType> { node };
            var current = node;
            while (current.ParentId != null)
            {
                var parent = all.FirstOrDefault(m => m.Id == current.ParentId);
                if (parent == null) break;
                path.Insert(0, parent);
                current = parent;
            }
            return path;
        }

    }
}
